import React, { useState, useEffect, useRef } from "react";
import Store from 'electron-store';
import { useDispatch } from 'react-redux';
import {Modal,Form, Input,Card,Button,Icon,message,} from "tea-component";
import { DEFAULT_SETTING_CONFIG } from '../../constants'
import { aesDecry, isWin, sleep } from '../../utils/tools';

// eslint-disable-next-line
import { Form as FinalForm, Field } from "react-final-form";
import Toast from "../../components/toast/Toast";
import { useSettingConfig } from "../../utils/react-use/useSettingConfig";
import { updateSettingConfig } from "../../store/actions/config";

const store = new Store();
const clearTmp = {
    userId: '',
    sdkappId: '',
    userSig: '',
    addressIp: '',
    port: '',
    publicKey: ''
}

function getStatus(meta, validating) {
    if (meta.active && validating) {
        return "validating";
    }
    if (!meta.touched) {
        return null;
    }
    return meta.error ? "error" : "success";
}

var isShowRge:boolean =false;
export const SettingConfig = () => {
    const [showModal, setShowModal ] = useState(false);
    const [errInf, setErrInf ] = useState("");
    const [showReg ,setShowReg ] = useState(isShowRge);
    const [defaultConfig, setDefaultConfig ] = useState(DEFAULT_SETTING_CONFIG);
    const { defaultser} = useSettingConfig();
    const [cheidx, setCheIdx] = useState(0);
    const [ipinf,setipinf] = useState("");
    const [urlServer,seturlServer] = useState(defaultser);
    const serlist = defaultConfig.serverlist;
    const dispatch = useDispatch();
    const request = require('request');

    async function onSubmit(values) {
        console.log(values);
        setErrInf("");
        if(values.password2!= values.password){
            setErrInf("确认密码必须与密码相同");
            return;
        }
        request.post(urlServer +'/api/app/member/register', {
            json: {
                nickName: values.nickName, //用户名
                password: values.password,
                username: values.username,
                type:1,
                clientType:"pc",
                headImg:""
            }
        }, (error, res, body) => {
            if (error) {
                setErrInf(error)
                return
            }
            console.log(body);
            if(body.code==200){
                dispatch(updateSettingConfig({userName:values.username,userPwd:values.password}));
                setShowModal(false);
            }else{
                setErrInf(body.message);
            }
        });
    }

    const clearConfig = () => {
        setShowModal(false)
    }

    useEffect(() => {
        const configSetting = store.get('setting-config') as State.SettingConfig;
        // @ts-ignore
        if(configSetting) {
            let newstate:any = configSetting;
            newstate.sdkappId = configSetting.sdkappId ?configSetting.sdkappId:defaultConfig.sdkappId;
            newstate.userName = configSetting.userName ?configSetting.userName:defaultConfig.userName;
            newstate.sdkappId = configSetting.userPwd ?configSetting.userPwd:defaultConfig.userPwd;
            setDefaultConfig(newstate);
            //dispatch(updateSettingConfig(configSetting));
        } else {
            // setShowModal(true);
        }
    }, []);

    useEffect(() => {
        if(showModal) {
            const configSetting = store.get('setting-config') as State.SettingConfig;
            let newstate:any = configSetting||{};
            newstate.sdkappId = configSetting?.sdkappId ?configSetting.sdkappId:defaultConfig.sdkappId;
            newstate.userName = configSetting?.userName ?configSetting.userName:defaultConfig.userName;
            newstate.sdkappId = configSetting?.userPwd ?configSetting.userPwd:defaultConfig.userPwd;
            setDefaultConfig(newstate);
        }
    }, [showModal]);

    useEffect(()=>{
        const serurl = urlServer||aesDecry( serlist[cheidx%serlist.length])
        if(serurl?.length>0){
            request.post(urlServer+'/api/app/sysConfig/getByCodeList',{       
                    json: {
                        codeList:['open_def_group',"can_register","speaking_interval","contacts_friends","group_size","group_type","is_user_status","is_message_read","is_friends_be_allowed","maximum_of_creations"]
                        }
                },(error, res) => {
                    if (error) {
                        setCheIdx(cheidx+1);
                        seturlServer(aesDecry( serlist[cheidx%serlist.length]));
                        return
                    }
                    if(res.body.code==200){
                        const data = res.body.data;
                        const config = data?.reduce((pre,cur)=>{
                            pre[cur.code]= cur.value; 
                            return pre;
                        }, {});
                        if(config?.can_register == "1"){
                            isShowRge = true;
                            setShowReg(true)
                        }
                        Toast.serConfig = config;
                        console.log(config)
                    }else{
                        console.log(res.body)
                        Toast.serConfig={};
                    }
            });
        }
    },[urlServer])
    const handlegetIp =()=>{
        const serurl = Toast.defaultser.length>1? Toast.defaultser:urlServer;
        request.get(serurl+'/api/app/member/ipInfo',{},(error, res) => {   
            if(error) return;
            let body = JSON.parse(res.body);
            if(body.code==200){
                setipinf(body.data.ip);
            }  
            //console.log(res);
        });
    }
    const handleOpenSettingModal = () => setShowModal(true);
    const pwdInputRef = useRef(null);

    const topStyle = isWin ? '35px' : '10px';

    return (
        <div style={{textAlign: "center", paddingTop: '20px', zIndex: 10000} } >
            <label onClick={handlegetIp}>获取IP</label>
            {showReg?<label onClick={handleOpenSettingModal} style={{marginLeft:"50px"}}>用户注册</label>:null}
            <div style={{color:"blue",margin:"15px"}} >{ipinf}</div>
            <Modal onClose={()=>{setShowModal(false)}}  visible={showModal} >
                <Modal.Body >
                    <div className="example-stage" >
                        <Card>
                            <Card.Body>
                                <FinalForm  initialValues={defaultConfig} onSubmit={onSubmit}>
                                    {({ handleSubmit, validating, submitting }) => {
                                        return (
                                            <form onSubmit={handleSubmit}>
                                                <Form.Title>新用户注册</Form.Title>
                                                <Form>
                                                    <Field   name="username"  validateOnBlur  validateFields={[]}
                                                        validate={async value => {
                                                            await sleep(1500);
                                                            let reg = /^[a-zA-Z]\w{5,17}$$/;  
                                                            return value && reg.test(value)?  undefined:"字母开头6-18位，不含特殊字符";
                                                        }}
                                                    >
                                                        {({ input, meta }) => (
                                                            <Form.Item  label="用户名" status={getStatus(meta, validating)}
                                                                message={
                                                                    getStatus(meta, validating) === "error" &&
                                                                    meta.error
                                                                }
                                                            >
                                                                <Input {...input} autoComplete="off" size="full" placeholder="请填写用户名" />
                                                            </Form.Item>
                                                        )}
                                                    </Field>
                                                    <Field  name="nickName" validateOnBlur validateFields={[]}
                                                        validate={async value => {
                                                            await sleep(1500);
                                                            return !value ? "必填项" : undefined;
                                                        }}
                                                    >
                                                        {({ input, meta }) => (
                                                            <Form.Item
                                                                label="昵称"
                                                                status={getStatus(meta, validating)}
                                                                message={
                                                                    getStatus(meta, validating) === "error" &&
                                                                    meta.error
                                                                }
                                                            >
                                                                <Input {...input} size="full" autoComplete="off"  placeholder="请填写昵称"/>
                                                            </Form.Item>
                                                        )}
                                                    </Field>
                                                    <Field  name="password"  validateOnBlur  validateFields={[]}
                                                        validate={async value => {
                                                            await sleep(1500);
                                                            let reg = /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[a-z])\S*$/;  
                                                            return value && reg.test(value)?  undefined:"密码至少包含小写字母、数字,且不少于6位";
                                                        }}
                                                    >
                                                        {({ input, meta }) => (
                                                            <Form.Item  label="密码" status={getStatus(meta, validating)}
                                                                message={
                                                                    getStatus(meta, validating) === "error" &&
                                                                    meta.error
                                                                }
                                                            >
                                                                <Input {...input} ref ={pwdInputRef} autoComplete="off" size="full" placeholder="请填写密码" />
                                                            </Form.Item>
                                                        )}
                                                    </Field>
                                                    <Field  name="password2" validateOnBlur validateFields={[]}
                                                        validate={async value => {
                                                            await sleep(1000);
                                                            return value==pwdInputRef.current.value? undefined:"请确认密码";
                                                        }}
                                                    >
                                                        {({ input, meta }) => (
                                                            <Form.Item label="确认密码" status={getStatus(meta, validating)}
                                                                message={
                                                                    getStatus(meta, validating) === "error" &&
                                                                    meta.error
                                                            }>
                                                                <Input {...input} autoComplete="off"  size="full" placeholder="请填写确认密码"/>
                                                            </Form.Item>
                                                        )}
                                                    </Field>
                                                </Form>
                                                <Form.Action>
                                                    <Button  type="primary" htmlType="submit" loading={submitting}>
                                                        提交
                                                    </Button>
                                                    <Button onClick={clearConfig}>取消</Button>
                                                </Form.Action>
                                            </form>
                                        );
                                    }}
                                </FinalForm>
                            </Card.Body>
                            { errInf.length>0? <div style={{textAlign:"center",color:"red"}}>错误信息：{errInf}</div>:null }
                        </Card>
                    </div>
                </Modal.Body>
            </Modal>
        </div>
    )
};